import sqlite3
from pathlib import Path


class Database:
    def __init__(self):
        # 确认数据库路径正确
        self.db_path = Path(__file__).parent.parent.parent / 'database' / 'hairsalon.db'
        print(f"数据库路径：{self.db_path}")  # 添加调试输出
        self.db_path.parent.mkdir(parents=True, exist_ok=True)

        self.conn = None
        self.cursor = None

    def connect(self):
        if self.conn is None:
            try:
                self.conn = sqlite3.connect(str(self.db_path))
                print("数据库连接成功")  # 添加连接成功提示
                self.conn.row_factory = sqlite3.Row
                self.cursor = self.conn.cursor()
            except Exception as e:
                print(f"数据库连接失败：{str(e)}")
                raise

    def disconnect(self):
        if self.conn:
            self.conn.close()
            self.conn = None  # 确保连接被清空

    def begin_transaction(self):
        self.connect()
        self.cursor.execute("BEGIN TRANSACTION")

    def commit(self):
        if self.conn:
            self.conn.commit()

    def rollback(self):
        if self.conn:  # 确保连接是打开的
            self.conn.rollback()
        else:
            print("无法回滚：数据库连接已关闭")

    def execute(self, sql, params=()):
        try:
            self.connect()  # 确保连接是打开的
            self.cursor.execute(sql, params)
            self.conn.commit()
            print(f"成功执行SQL：{sql} \n参数：{params}")
            return self.cursor.rowcount > 0
        except Exception as e:
            print(f"执行失败：{str(e)}")
            self.rollback()  # 回滚事务
            return False
        finally:
            self.disconnect()

    def fetch_all(self, sql, params=()):
        try:
            self.connect()  # 确保每次操作前连接数据库
            self.cursor.execute(sql, params)
            return self.cursor.fetchall()
        except Exception as e:
            print(f"查询失败：{str(e)}")
            return []
        finally:
            self.disconnect()  # 操作完成后断开连接

    def fetch_one(self, sql, params=()):
        try:
            self.connect()  # 确保每次操作前连接数据库
            self.cursor.execute(sql, params)
            return self.cursor.fetchone()
        except Exception as e:
            print(f"查询失败：{str(e)}")
            return None
        finally:
            self.disconnect()  # 操作完成后断开连接

    def table_exists(self, table_name):
        query = "SELECT name FROM sqlite_master WHERE type='table' AND name=?"
        return self.fetch_one(query, (table_name,)) is not None


# 创建数据库单例
db = Database()
